package com.qixin.api.serviceimpl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qixin.api.bean.ComUser;
import com.qixin.api.bean.ResultPage;
import com.qixin.api.bean.TotalRoleUser;
import com.qixin.api.bean.VoPage;
import com.qixin.api.bean.pojo.WelcomCount;
import com.qixin.api.mapper.ComUserMapper;
import com.qixin.api.service.ComUserService;
import com.qixin.api.service.TotalMenuResourseService;
import com.qixin.api.service.TotalRoleUserService;
import com.qixin.util.cache.EhcacheUtil;
import com.qixin.util.sms.SmsMark;
import com.qixin.util.sms.SmsUtil;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 冯政尚
 * @since 2018-10-25
 */
@Service
public class ComUserServiceImpl extends ServiceImpl<ComUserMapper, ComUser> implements ComUserService {
    @Autowired
    TotalMenuResourseService totalMenuResourseService;
    @Autowired
    TotalRoleUserService totalRoleUserService;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ComUserServiceImpl.class);
     @Override
       public String SendSMS(Long phone) {
        SendSmsResponse response;
        String code= SmsMark.getCode();

        try {
            response =  SmsUtil.sendSms(phone + "", SmsMark.SMS_MARK, code);
        } catch (ClientException e) {
            e.printStackTrace();
            return  "服务器出错，请稍后再试";
        }
        if(response.getMessage().equals("OK")){
            //存进cache缓存  180后过期  当访问过一次后 60秒内没有再此访问 同样过期 缓存区的key设置成数字加字符串 否则获取不到
            EhcacheUtil.put("SMS", phone + "Data", code);
           logger.info("用户手机号："+phone);
         logger.info("用户输入的验证码："+code);
           return  "获取验证码成功";
        }
        return "获取短信验证码失败";
   }

    @Override
    public boolean equalsCache(String code,String callPhone) {

        //从缓存中获取六位验证码 当访问过一次后 60秒内没有再此访问会过期  缓存区的key设置成数字加字符串 否则获取不到
        String cacheCode=EhcacheUtil.get("SMS",callPhone+"Data")+"";
        logger.info("缓存中的验证码："+cacheCode);
        logger.info("用户输入的验证码："+code);
        logger.info("用户手机号："+callPhone);
        if (code.equals(cacheCode)){
            return true;
        }
        return false;
    }


    @Override
    public boolean login(ComUser comUser, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone",comUser.getCallPhone());
        map.put("pass_word", comUser.getPassword());
        List<ComUser> comUsers = baseMapper.login(map);
         //如果用户存在，放入session域
        if(comUsers.size()>0) {
            comUsers.get(0).getTotalRole().setTotalMenuResourses(totalMenuResourseService.findMenuByRole(comUsers.get(0).getTotalRole()));
            System.err.print(comUsers.get(0).toString());
            session.setAttribute("user", comUsers.get(0));
            return  true;
        }else {
            return false;
        }
    }

    @Override
    public boolean registerUser(ComUser comUser,String param) {
        //把传过来的json字符串转成Map集合
        Map mapObj = JSONObject.parseObject(param, Map.class);
        long roleId=Long.parseLong(mapObj.get("roleId")+"");
        if(this.insert(comUser)){
            Long id=comUser.getId();
            TotalRoleUser totalRoleUser=new TotalRoleUser();
            totalRoleUser.setRoleId(roleId);
            totalRoleUser.setUserId(id);
            System.out.print(roleId);
            System.out.print(id);
            if(totalRoleUserService.insert(totalRoleUser)){
                return  true;
            }

        }
        return false;
    }


//修改密码
    @Override
    public boolean update(ComUser comUser, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone",comUser.getCallPhone());
        map.put("pass_word", comUser.getPassword());
        List<ComUser> comUsers = baseMapper.login(map);
        boolean flag=false;
        if (comUsers.size() > 0) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("user_name", comUser.getCallPhone());
            paramMap.put("newpassword1", comUser.getNewpassword1());
            Integer password = baseMapper.updatepassworda(paramMap);
            if (password==null) {
                flag=true;
            }else flag=false;
        }
        return flag;

    }

    @Override
    public ResultPage<ComUser> findUserAndRole(VoPage voPage,ComUser comUser) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1)*voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<ComUser> list = baseMapper.findUserAndRole(paramMap,comUser);
        Integer count = baseMapper.countMyPage(paramMap,comUser);
        ResultPage<ComUser>resultPage=new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }
    @Override
    @Transactional(rollbackFor = {SQLException.class})
    public String deleteUser(Long id) throws SQLException {
        Map map=new HashMap<>();
        map.put("user_id",id);
        if(totalRoleUserService.deleteByMap(map)){
            if(this.deleteById(id)){
                return "删除成功";
            }
        }
        throw  new  SQLException();
    }

    @Override
    public WelcomCount findWelcomCount() {
        return baseMapper.findWelcomCount();
    }

}
